package com.web.kdl.config.security;

import com.web.kdl.config.security.components.AuthUser;
import com.web.kdl.entity.user.UserInfo;
import com.web.kdl.service.user.UserService;
import com.web.kdl.util.RedisUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * @Author： shulibin
 * @Date： 2025/7/28 9:10
 * @Describe：
 */
@Service
public class UserDetailService implements UserDetailsService {

    @Autowired
    UserService userService;
    
    @Autowired
    RedisUtils redisUtils;
    
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 检查用户是否被锁定
        String lockKey = AuthConstants.REDIS_KEY_LOGIN_LOCK + username;
        Boolean isLocked = redisUtils.getBoolean(lockKey);
        if (Boolean.TRUE.equals(isLocked)) {
            throw new UsernameNotFoundException("账号已被锁定，请5分钟后重试");
        }
        
        UserInfo user = userService.findByUsername(username);
        if(Objects.isNull(user)){
            throw new UsernameNotFoundException("User not Found.");
        }
        String email=user.getEmail();
        List<String> permissions = userService.listAuthorityById(String.valueOf(user.getId()));
        List<GrantedAuthority> authorities = new ArrayList<>(permissions.size());
        permissions.forEach( item -> authorities.add(new SimpleGrantedAuthority(item)));

        return new AuthUser(String.valueOf(user.getId()),username, user.getPassword(),email,user.getRole() ,authorities);
    }
}

